package com.acc.store.service.impl;


import com.acc.store.dto.UserDto;
import com.acc.store.entity.User;
import com.acc.store.mapper.UserMapper;
import com.acc.store.service.UserService;
import com.acc.store.utils.JWTUtils;
import com.acc.store.vo.UserVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.Map;

/**
 * @author 10067
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2023-10-13 18:05:21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public IPage<User> getPage(Map<String, Object> params) {

        //提取参数
        Long page = Long.valueOf((String) params.get("page"));
        Long limit = Long.valueOf((String) params.get("limit"));
        String name = (String) params.get("name");
        //封装查询语句
        Page<User> page1 = lambdaQuery().like(!StringUtils.isNullOrEmpty(name)
                , User::getName, name).page(new Page<>(page, limit));


        return page1;
    }

    @Override
    public UserVo login(UserDto userDto) {
        User byId = getById(userDto.getUserId());
        if(byId.getStatus()==0) {
            return null;
        }
        if (byId==null){
            return null;
        }
        boolean flag = byId.getPassword().equals(userDto.getPassword());
        if (flag) {
            log.error(userDto.toString());
            String token = new JWTUtils().createToken(userDto.getUserId());
            UserVo userVo = new UserVo();
            userVo.setId(userDto.getUserId());
            userVo.setLevel(byId.getPermissionLevel());
            userVo.setToken(token);
            return userVo;
        } else {
            return null;
        }
    }

    @Override
    public Long saveInfo(User user) {
        user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        if(user.getAvatar().isEmpty()){
            user.setAvatar("https://acctest.oss-cn-beijing.aliyuncs.com/acc-store/e176fc31-ae0f-41ea-b10b-adcf26535cbb.jpg");
        }
        save(user);
        return user.getId();
    }
}




